package com.qhgrain.app.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.paas.base.modules.utils.lang.StringUtil;
import com.paas.base.modules.utils.page.PageBean;
import com.qhgrain.app.constant.UrlEnum;
import com.qhgrain.app.controller.IndexController;
import com.qhgrain.app.util.ConfigUtil;
import com.qhgrain.app.vo.AppGroupVo;
import com.qhgrain.app.vo.UserVo;
import com.qhgrain.gway.util.HttpUtil;
import com.sun.star.uno.RuntimeException;

@Service
public class UserService {

	
	private static Logger LOG = LoggerFactory.getLogger(UserService.class);

	private final static String BASE_URL = ConfigUtil.getProperties(UrlEnum.USER);

	
	public List<UserVo> getUsersByRoleId(String roleId) throws Exception{
		try {
			String vo = HttpUtil.get(BASE_URL+"/user/get/users/"+roleId, new HashMap<String,String>());
			JSONObject voJson = JSONObject.parseObject(vo);
			if("1".equals(voJson.getString("state"))){
				return JSONArray.parseArray(voJson.getString("data"), UserVo.class);
			}else{
				throw new RuntimeException("api根据角色id获取用户出错...."+vo);
			}
		} catch (Exception e) {
			LOG.error("api根据角色id获取用户出错..",e);
			throw e;
		}
	}
	/**
	 * 根据loginName获取用户信息
	 * @param loginName
	 * @return
	 * @throws IOException 
	 */
	public UserVo findByLoginName(String loginName) throws IOException{
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("loginName", loginName);
		String vo = HttpUtil.postFormParams(BASE_URL,"/user/query/userByLoginName", map);
		JSONObject voJson = JSONObject.parseObject(vo);
		if ("1".equals(voJson.getString("state"))) {
			UserVo userVo = JSONObject.parseObject(voJson.getString("data"), UserVo.class);
			return userVo;
		} else {
			LOG.error("根据loginName从api获取用户数据失败..." + vo);
			throw new RuntimeException("根据loginName从api获取用户数据失败..." + vo);
		}
	}
	public boolean isExist(String loginName) throws Exception {
		UserVo userVo = findByLoginName(loginName);
		if(userVo != null){
			return false;
		}
		return true;
		
		

	}
	public  boolean postUserAppGroups(String userId,String appGroupIds) throws IOException {
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("userId",userId);
		params.put("appGroupIds", appGroupIds);
		String vo = HttpUtil.post(BASE_URL+"/userAppGroup/post/userAppGroups", params);
		JSONObject voJson = JSONObject.parseObject(vo);
		if ("1".equals(voJson.getString("state"))) {
			return true;
		} else {
			LOG.error("从api获取应用群组数据失败..." + vo);
			return false;
		}
	}
	
	/**
	 * 根据用户id获取对应的应用群组,id为null查所有应用群组
	 * @param userId
	 * @return
	 */
	public List<AppGroupVo> queryByUserId(String userId)throws Exception{
		try {
			Map<String,Object> map = new HashMap<String,Object>();
			if(!StringUtil.isBlank(userId)){
				map.put("userId", userId);
			}
			String vo = HttpUtil.post(BASE_URL+ "/userAppGroup/query/appGroupsByUserId", map);
			JSONObject voJson = JSONObject.parseObject(vo);
			if("1".equals(voJson.getString("state"))){
				return JSONArray.parseArray(voJson.getString("data"), AppGroupVo.class);
			}else{
				LOG.error("应用群组查询，api失败..."+vo);
				throw new RuntimeException("应用群组查询，api失败..."+vo);
			}
		} catch (Exception e) {
			throw e;
		}
	}
	/**
	 * 分页查询用户
	 * @param userName
	 * @param loginName
	 * @param unitName
	 * @param postName
	 * @param status
	 * @return
	 */
	public PageBean<UserVo> queryPage(String userName,String loginName,String unitId,String unitName,String postId,String postName,String status,int pageNo,int pageSize)throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtil.isNotBlank(loginName)) {
			map.put("loginName", loginName.trim());
		}
		if (StringUtil.isNotBlank(userName)) {
			map.put("userName", userName.trim());
		}
		if(StringUtil.isNotBlank(unitId)){
			map.put("unitId", unitId.trim());
		}
		if (StringUtil.isNotBlank(unitName)) {
			map.put("unitName", unitName.trim());
		}
		if(StringUtil.isNotBlank(postId)){
			map.put("postId", postId.trim());
		}
		if (StringUtil.isNotBlank(postName)) {
			map.put("postName", postName.trim());
		}
		if (StringUtil.isNotBlank(status)) {
			map.put("status",status.trim());
		}
		map.put("pageNo", pageNo);
		map.put("pageSize", pageSize);
		//返回当前登录用户所在及子部门的用户(admin用户返回全部)
		String currentUserLoginName = IndexController.getLoginName();
		System.out.println(currentUserLoginName);
		if(StringUtil.isNotBlank(currentUserLoginName) && !"admin".equals(currentUserLoginName)){
			map.put("currentUserLoginName", currentUserLoginName);
		}
		String requestVo;
		try {
			requestVo = HttpUtil.postFormParams(BASE_URL, "/user/query", map);
			JSONObject voJson = JSONObject.parseObject(requestVo);

			if ("1".equals(voJson.getString("state"))) {
				
				JSONObject data = JSONObject.parseObject(voJson.getString("data"));

				PageBean<UserVo> pageBean = new PageBean<UserVo>(pageNo,pageSize);
				List<UserVo> list = JSONArray.parseArray(data.getString("list"), UserVo.class);
				int count = data.getIntValue("count");
				pageBean.setData(list);
				pageBean.setTotalCount(count);
				
				return pageBean;
			} else {
				LOG.error("用户分页查询,api出错。。。。" + requestVo);
				throw new RuntimeException("用户分页查询,api出错。。。。" + requestVo);
			}

		} catch (IOException e) {
			LOG.error("用户分页查询出错。。。。", e);
			throw e;
		}
	}
	/**
	 * 根据组织，角色获取用户
	 * @param roleId
	 * @param roleCode
	 * @param unitId
	 * @return
	 * @throws IOException 
	 */
	public List<UserVo> getUsersByRoleAndUnit(String roleId,String roleCode,String unitId,boolean isContainNextLevel) throws IOException{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("roleId", roleId);
		map.put("roleCode", roleCode);
		map.put("unitId", unitId);
		map.put("isContainNextLevel", isContainNextLevel?"1":"0");
		
		String vo = HttpUtil.post(BASE_URL+"/user/getUsersBy", map);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("1".equals(voJson.getString("state"))){
			return JSONObject.parseArray(voJson.getString("data"), UserVo.class);
		}else{
			LOG.error("根据组织，角色获取用户信息，api失败...vo="+vo);
			throw new RuntimeException("根据组织，角色获取用户信息，api失败...vo="+vo);
		}
	}
}
